package com.njbw.tool;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 编解码工具
 */
public class EncodeUtil {

    private final static String DEFAULT_URL_ENCODING = StandardCharsets.UTF_8.name();
    private final static Base64.Encoder BASE64_ENCODER = Base64.getEncoder();
    private final static Base64.Decoder  BASE64_DECODER = Base64.getDecoder();

    /**
     * BASE64 编码
     */
    public static String encode(String text) throws UnsupportedEncodingException {
        byte[] textByte = text.getBytes(DEFAULT_URL_ENCODING);
        return BASE64_ENCODER.encodeToString(textByte);
    }

    /**
     * BASE64 解码
     */
    public static String decode(String encodedText) throws UnsupportedEncodingException {
        return new String(BASE64_DECODER.decode(encodedText), DEFAULT_URL_ENCODING);
    }

    /**
     * URL 编码
     */
    public static String urlEncode(String part) throws UnsupportedEncodingException {
        return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
    }

    /**
     * URL 解码
     */
    public static String urlDecode(String encodePart) throws UnsupportedEncodingException {
        return URLDecoder.decode(encodePart, DEFAULT_URL_ENCODING);
    }
}
